package com.guslegend.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.guslegend.enums.BizCodeEnum;
import com.guslegend.enums.SendCodeEnum;
import com.guslegend.component.MailService;
import com.guslegend.service.NotifyService;
import com.guslegend.util.CommonUtil;
import com.guslegend.util.JsonData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.util.concurrent.TimeUnit;

/**
 * @author: guslegend
 * @description: 图片验证码
 * @create: 2025-05-25 21:10
 **/
@Api(tags = "通知模块")
@RestController
@RequestMapping("/api/notify/v1")
@Slf4j
public class NotifyController {
    @Autowired
    private DefaultKaptcha kaptcha;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private NotifyService notifyService;

    private static final int KAPTCHA_EXPIRE = 10 * 60 * 1000;

    @ApiOperation("获取图形验证码")
    @GetMapping("get_kaptcha")
    public void getKaptcha(HttpServletRequest request, HttpServletResponse response) {
//        生成验证码
        String kaptchaText = kaptcha.createText();
        log.info("图形验证码：{}", kaptchaText);
//        生成验证码图片，并且通过response输出流流输出
        BufferedImage bufferedImage = kaptcha.createImage(kaptchaText);
        //将图形验证码存入redis
        redisTemplate.opsForValue().set(getKaptchaCacheKey(request), kaptchaText, KAPTCHA_EXPIRE, TimeUnit.MILLISECONDS);
        try (ServletOutputStream outputStream = response.getOutputStream()) {
            ImageIO.write(bufferedImage, "jpg", outputStream);
        } catch (Exception e) {
            log.error("验证码异常：{}", e.getMessage());
        }
    }

    @ApiOperation("注册验证码")
    @GetMapping("get_register_code")
    public JsonData sendRegisterCode(@RequestParam(value = "to") String to, @RequestParam(value = "kaptcha") String kaptcha, HttpServletRequest request) {
        return sendCode(to, kaptcha, request, SendCodeEnum.USER_REGISTRY);
    }

    @ApiOperation("登录验证码")
    @GetMapping("get_login_code")
    public JsonData sendLoginCode(@RequestParam(value = "to") String to, @RequestParam(value = "kaptcha") String kaptcha, HttpServletRequest request) {
        return sendCode(to, kaptcha, request, SendCodeEnum.USER_LOGIN);
    }

    @ApiOperation("修改密码验证码")
    @GetMapping("get_change_pwd__code")
    public JsonData sendChangePwdCode(@RequestParam(value = "to") String to, @RequestParam(value = "kaptcha") String kaptcha, HttpServletRequest request) {
        return sendCode(to, kaptcha, request, SendCodeEnum.USER_CHANGE_PASSWORD);
    }


    /**
     * @Description: 生成缓存的key
     */
    private String getKaptchaCacheKey(HttpServletRequest request) {
//        通过用户的ip地址跟浏览器 唯一标识一个图形验证码
        String ipAddr = CommonUtil.getIpAddr(request);
        String userAgent = request.getHeader("User-Agent");
        log.info("IP:{}", ipAddr);
        log.info("User_Agent:{}", userAgent);
        return "kaptcha:" + CommonUtil.MD5(ipAddr + userAgent);
    }

    /**
     * 发送邮箱验证码
     * @param to
     * @param kaptcha
     * @param request
     * @param sendCodeEnum
     * @return
     */
    public JsonData sendCode(@RequestParam(value = "to") String to, @RequestParam(value = "kaptcha") String kaptcha, HttpServletRequest request, SendCodeEnum sendCodeEnum) {
        log.info("to: {}", to);
        log.info("kaptcha: {}", kaptcha);
        //        做非空判断
        if (to != null && kaptcha != null && !to.equals("") && !kaptcha.equals("")) {
            String cacheKaptcha = (String) redisTemplate.opsForValue().get(getKaptchaCacheKey(request));
//            图形验证码正确 发送邮箱验证码或者手机验证码
            if (kaptcha.equalsIgnoreCase(cacheKaptcha)) {
                return notifyService.sendCode(sendCodeEnum, to);
            } else {
//                图形验证码错误
                return JsonData.buildResult(BizCodeEnum.CODE_CAPTCHA_ERROR);
            }
        } else {
            return JsonData.buildError("请求的值不能为空！");
        }
    }
}